/**
 * ================================
 * 企业备案人员选择
 * ================================
 */

import { DoubleRightOutlined } from '@ant-design/icons';
import { Input } from 'antd';
import classNames from 'classnames';
import { cloneDeep, uniqBy } from 'lodash-es';
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import type { YmDialogProps, YmTabsProps } from 'ym-design';
import { YmDialog, YmTabs } from 'ym-design';

import Ostyle from './YmRegisterPersonModal.less';

import { useAppSelector } from '@/redux/store';
import { useRequest } from 'ahooks';
import CheckboxList, { CheckboxItem } from './CheckboxList';
import {
  AssociationTreeDataVO,
  getAssociationTreeData,
  getPersonListByEntId,
  getPositionListByEntId,
  PersonDataVO,
  PositionDataVO,
} from './data';
import type { YmChoiceStaffModalProps } from './interface';
import SelectedItemList from './SelectedItemList';

type TRef = {
  open: () => void;
};

const YmRegisterPersonModal = forwardRef<TRef, YmChoiceStaffModalProps>((props, ref) => {
  const { entId } = useAppSelector((state) => state.loginEnt);

  const { modalPorps = {}, value, defaultValue, choiceBtn = 'checkbox', onChange } = props;
  const [open, setOpen] = useState<boolean>(false);
  const [tabActiveKey, setTabActiveKey] = useState<string>('1');

  const [isLoading, setLoading] = useState<boolean>(false);

  // Data Source
  const [personDataList, setPersonDataList] = useState<CheckboxItem[]>([]);
  const [associationDataList, setAssociationDataList] = useState<CheckboxItem[]>([]);
  const [positionDataList, setPositionDataList] = useState<CheckboxItem[]>([]);

  // Checked  Item List
  const [checkedPersonItemList, setCheckedPersonItemList] = useState<CheckboxItem[]>([]);
  const [checkedAssociationItemList, setCheckedAssociationItemList] = useState<CheckboxItem[]>([]);
  const [checkedPositionItemList, setCheckedPositionItemList] = useState<CheckboxItem[]>([]);
  // Checked Id List
  const [checkedPersonIdList, setCheckedPersonIdList] = useState<string[]>([]);
  const [checkedAssociationIdList, setCheckedAssociationIdList] = useState<string[]>([]);
  const [checkedPositionIdList, setCheckedPositionIdList] = useState<string[]>([]);

  const mergedCheckedItemsRef = useRef<CheckboxItem[]>([]);
  const mergedCheckedIdsRef = useRef<string[]>([]);

  const [total, setTotal] = useState<number>(0);
  const pageIndexRef = useRef<number>(1);
  const enterprisePageIndexRef = useRef<number>(1);
  const positionPageIndexRef = useRef<number>(1);
  const [selectedEnterprisePersonTotal, setSelectedEnterprisePersonTotal] = useState<number>(0);
  const [selectedPositionPersonTotal, setSelectedPositionPersonTotal] = useState<number>(0);

  // const [isNextLevel, setIsNextLevel] = useState<boolean>(false);

  const isNextLevelRef = useRef<boolean>(false);

  const [selectedLevelItem, setSelectedLevelItem] = useState<CheckboxItem>();

  // Breakcrumb List
  const [crumbList, setCrumbList] = useState<CheckboxItem[]>([]);

  const [realCheckedItems, setRealCheckedItems] = useState<CheckboxItem[]>(value ?? []);

  // dialog destoryOnClose:false时，每次点击确认保存 mergeValue，如果下一次一番操作之后点击取消按钮可以复原到initialMergeValue;
  const [initialMergeValue, setInitialMergeValue] = useState<CheckboxItem[]>(() => {
    if (value !== undefined) {
      return cloneDeep(value);
    } else if (defaultValue !== undefined) {
      return cloneDeep(defaultValue);
    } else {
      return [];
    }
  });

  // 初始化mergeValue值，注：用useSate包裹就意味着，组件挂载成功后就只能通过setMergeValue来更改mergeValue，尽管props变化了
  const [mergeValue, setMergeValue] = useState<CheckboxItem[] | undefined>(() => {
    if (value !== undefined) {
      return value;
    } else {
      return defaultValue;
    }
  });

  useEffect(() => {
    setRealCheckedItems(value ?? []);

    setCheckedPersonItemList(value ? value?.filter((item) => item.checked) : []);
    setCheckedPersonIdList(value ? value?.filter((item) => item.checked).map((v) => v.id) : []);

    mergedCheckedItemsRef.current = value ?? [];
  }, [value]);

  // modalPorps.open 控制dialog
  useEffect(() => {
    if (typeof modalPorps.open === 'boolean') {
      setOpen(modalPorps.open);
    }
  }, [modalPorps.open]);

  useImperativeHandle(ref, () => ({
    open: () => {
      setOpen(true);
    },
    close: () => {
      setOpen(false);
    },
  }));

  // 通过modalProps.open传参 open受控，否则不受控
  const internaleClose = (e: any) => {
    if (typeof modalPorps.open === 'boolean') {
      modalPorps.onClose?.(e);
    } else {
      setOpen(false);
    }
  };

  // 取消
  const internaleCancle = (e: React.SyntheticEvent) => {
    if (typeof modalPorps.open === 'boolean') {
      modalPorps.onCancel?.(e);
    } else {
      setOpen(false);
    }
  };

  const choiceTabItems = useMemo(() => {
    const tempTabItems: YmTabsProps['items'] = [
      {
        key: '1',
        label: '全部人员',
      },
      {
        key: '2',
        label: '备案企业',
      },
      {
        key: '3',
        label: '人员类型',
      },
    ];

    return tempTabItems;
  }, []);

  const tempMergedCheckedItems = useMemo(() => {
    const uniquedCheckedItems = uniqBy(
      [...checkedPersonItemList, ...checkedAssociationItemList, ...checkedPositionItemList],
      'id',
    );

    return uniquedCheckedItems;
  }, [checkedPersonItemList, checkedAssociationItemList, checkedPositionItemList]);

  const tempMergedDataList = useMemo(() => {
    const uniquedDataList = uniqBy([...personDataList, ...associationDataList, ...positionDataList], 'id');

    return uniquedDataList;
  }, []);

  // modal
  const mergeModlaProps: YmDialogProps = useMemo(() => {
    const { styles = {}, ...restModalPorps } = modalPorps || {};
    if (styles.body) {
      styles.body = {
        ...styles.body,
        padding: '16px 24px',
      };
    } else {
      styles.body = { padding: '16px 24px' };
    }
    const tempModalProps = {
      destroyOnClose: false,
      title: '选择人员',
      ...restModalPorps,
      styles,
      open,
      onClose: internaleClose,
      onCancel: internaleCancle,
      onOk: (e: React.SyntheticEvent) => {
        const tempMergeValue = mergeValue || [];

        if (!restModalPorps.destroyOnClose) {
          setInitialMergeValue(cloneDeep(tempMergeValue));
        }

        if (typeof restModalPorps.onOk === 'function') {
          restModalPorps.onOk(e, mergedCheckedItemsRef.current);
        } else {
          internaleClose(null);
          onChange?.(mergedCheckedItemsRef.current);
        }
      },
    };
    return tempModalProps;
  }, [open, mergeValue, modalPorps]);

  /**
   * tab change
   *
   * @param activeKey
   */
  const handleChoiceTabChange = (activeKey: string) => {
    setTabActiveKey(activeKey);

    switch (activeKey) {
      case '1':
        setCheckedPersonItemList(realCheckedItems.filter((item) => item.type === '1'));
        setCheckedPersonIdList(realCheckedItems.filter((item) => item.type === '1').map((v) => v.id));
        break;
      case '2':
        setCrumbList([
          {
            uniquedKey: '2',
            id: '',
            name: '全部',
            type: '2',
            tab: '2',
            count: 0,
          },
        ]);

        setCheckedAssociationItemList(realCheckedItems.filter((item) => item.tab === '2' && item.type === '2'));
        setCheckedAssociationIdList(
          realCheckedItems.filter((item) => item.tab === '2' && item.type === '2').map((v) => v.id),
        );
        break;
      case '3':
        setCrumbList([
          {
            uniquedKey: '3',
            id: '',
            name: '全部',
            type: '3',
            tab: '3',
            count: 0,
          },
        ]);

        setCheckedPositionItemList(realCheckedItems.filter((item) => item.tab === '3' && item.type === '3'));
        setCheckedPositionIdList(
          realCheckedItems.filter((item) => item.tab === '3' && item.type === '3').map((v) => v.id),
        );
        break;
    }
  };

  /**
   * 搜索
   *
   * @param value
   */
  const onSearch = async (value: string) => {
    setTotal(0);
    setSelectedEnterprisePersonTotal(0);
    setSelectedPositionPersonTotal(0);

    pageIndexRef.current = 1;
    enterprisePageIndexRef.current = 1;
    positionPageIndexRef.current = 1;

    let response, tempDataList;

    setLoading(true);

    if (value) {
      // NOTE: 这里搜索都是查人员，所以直接都设置tab为1

      response = await getPersonListByEntId({ pageIndex: 1, pageSize: 99999, keyWords: value });

      tempDataList = (response?.list as PersonDataVO[]).map((item, index) => {
        return {
          uniquedKey: new Date().getTime() + index + '1',
          name: item.name,
          id: item.personId,
          phone: item.phone,
          avatar: item.icon,
          count: 0,
          type: '1',
          tab: '1',
        };
      });

      switch (tabActiveKey) {
        case '1': // 全部人员
          setPersonDataList(tempDataList);
          break;
        case '2': // 备案企业
          setAssociationDataList(tempDataList);

          setCheckedAssociationItemList(realCheckedItems.filter((item) => item.type === '1'));
          setCheckedAssociationIdList(realCheckedItems.filter((item) => item.type === '1').map((v) => v.id));

          break;
        case '3': // 人员类型
          setPositionDataList(tempDataList);

          setCheckedPositionItemList(realCheckedItems.filter((item) => item.type === '1'));
          setCheckedPositionIdList(realCheckedItems.filter((item) => item.type === '1').map((v) => v.id));

          break;
      }
    } else {
      switch (tabActiveKey) {
        case '1': // 全部人员
          response = await getPersonListByEntId({ pageIndex: 1, pageSize: 10 });

          tempDataList = (response?.list as PersonDataVO[]).map((item, index) => {
            return {
              uniquedKey: new Date().getTime() + index + '1',
              name: item.name,
              id: item.personId,
              phone: item.phone,
              avatar: item.icon,
              count: 1,
              type: '1',
              tab: '1',
            };
          });

          setPersonDataList(tempDataList);

          setTotal(response.total);
          break;

        case '2': // 备案企业
          response = await getAssociationTreeData({ type: 1, entId, count: true });

          tempDataList = (response?.list as AssociationTreeDataVO[]).map((item, index) => {
            return {
              uniquedKey: new Date().getTime() + index + '2',
              name: item.name,
              id: item.entId,
              avatar: item.icon,
              count: +item.count,
              type: '2',
              tab: '2',
            };
          });

          setAssociationDataList(tempDataList);

          setSelectedEnterprisePersonTotal(0);

          setCheckedAssociationItemList(realCheckedItems.filter((item) => item.tab === '2' && item.type === '2'));
          setCheckedAssociationIdList(
            realCheckedItems.filter((item) => item.tab === '2' && item.type === '2').map((v) => v.id),
          );

          break;
        case '3': // 人员类型
          response = await getPositionListByEntId({ entId });

          tempDataList = (response?.list as PositionDataVO[]).map((item, index) => {
            return {
              uniquedKey: new Date().getTime() + index + '3',
              name: item.name,
              id: item.code,
              count: +item.personNum,
              type: '3',
              tab: '3',
            };
          });

          setPositionDataList(tempDataList);

          setSelectedPositionPersonTotal(0);

          setCheckedPositionItemList(realCheckedItems.filter((item) => item.tab === '3' && item.type === '3'));
          setCheckedPositionIdList(
            realCheckedItems.filter((item) => item.tab === '3' && item.type === '3').map((v) => v.id),
          );

          break;
      }
    }

    setLoading(false);
  };

  const { loading } = useRequest(
    async () => {
      // 初始化分页相关参数
      setTotal(0);
      setSelectedEnterprisePersonTotal(0);
      setSelectedPositionPersonTotal(0);

      pageIndexRef.current = 1;
      enterprisePageIndexRef.current = 1;
      positionPageIndexRef.current = 1;

      switch (tabActiveKey) {
        case '1': // 全部人员
          return await getPersonListByEntId({ pageIndex: pageIndexRef.current, pageSize: 10 });
        case '2': // 备案企业
          return await getAssociationTreeData({ type: 1, entId, count: true });
        case '3': // 人员类型
          return await getPositionListByEntId({ entId });
      }
    },
    {
      onSuccess(data) {
        if (data) {
          let tempDataList;

          switch (tabActiveKey) {
            case '1': // 全部人员
              tempDataList = (data?.list as PersonDataVO[]).map((item, index) => {
                return {
                  uniquedKey: new Date().getTime() + index + '1',
                  name: item.name,
                  id: item.personId,
                  phone: item.phone,
                  avatar: item.icon,
                  count: 1,
                  type: '1',
                  tab: '1',
                };
              });

              setPersonDataList(tempDataList);

              setTotal(data.total);
              break;
            case '2': // 备案企业
              tempDataList = (data?.list as AssociationTreeDataVO[]).map((item, index) => {
                return {
                  uniquedKey: new Date().getTime() + index + '2',
                  name: item.name,
                  id: item.entId,
                  avatar: item.icon,
                  count: +item.count,
                  type: '2',
                  tab: '2',
                };
              });

              setAssociationDataList(tempDataList);
              break;
            case '3': // 人员类型
              tempDataList = (data?.list as PositionDataVO[]).map((item, index) => {
                return {
                  uniquedKey: new Date().getTime() + index + '3',
                  name: item.name,
                  id: item.code,
                  count: +item.personNum,
                  type: '3',
                  tab: '3',
                };
              });

              setPositionDataList(tempDataList);
              break;
          }
        }
      },
      refreshDeps: [tabActiveKey],
    },
  );

  /**
   * 复选框 - 选中事件
   *
   * @param checkedIds
   * @param checkedItems
   * @param type
   */
  const onCheckboxItemChange = (
    checkedIds: string[],
    checkedItems: CheckboxItem[],
    currentValue: string,
    isChecked: boolean,
    type: string,
  ) => {
    const filteredCheckboxItems = checkedItems.filter((item) => item.checked);
    const tempData = mergedCheckedItemsRef.current.filter((item) => item.checked);

    if (!isChecked) {
      mergedCheckedItemsRef.current = uniqBy([...tempData, ...filteredCheckboxItems], 'id').filter(
        (item) => item.checked && currentValue !== item.id,
      );

      setRealCheckedItems(mergedCheckedItemsRef.current.filter((item) => item.id !== currentValue));
    } else {
      mergedCheckedItemsRef.current = uniqBy([...tempData, ...filteredCheckboxItems], 'id').filter(
        (item) => item.checked,
      );

      setRealCheckedItems(mergedCheckedItemsRef.current);
    }

    switch (type) {
      case '1':
        setCheckedPersonItemList(filteredCheckboxItems);
        setCheckedPersonIdList(filteredCheckboxItems.map((item) => item.id));

        break;
      case '2':
        setCheckedAssociationItemList(filteredCheckboxItems);
        setCheckedAssociationIdList(filteredCheckboxItems.map((item) => item.id));

        break;
      case '3':
        setCheckedPositionItemList(filteredCheckboxItems);
        setCheckedPositionIdList(filteredCheckboxItems.map((item) => item.id));

        break;
    }
  };

  /**
   * 复选框 - 全选
   *
   * @param checkedIds
   * @param checkedItems
   * @param type
   */
  const onAllCheckboxItemChange = (
    checkedIds: string[],
    checkedItems: CheckboxItem[],
    currentValue: string[],
    isChecked: boolean,
    type: string,
  ) => {
    const filteredCheckboxItems = checkedItems.filter((item) => item.checked);
    const tempData = mergedCheckedItemsRef.current.filter((item) => item.checked);

    if (!isChecked) {
      mergedCheckedItemsRef.current = uniqBy([...tempData, ...filteredCheckboxItems], 'id').filter(
        (item) => item.checked && !currentValue.includes(item.id),
      );

      setRealCheckedItems(mergedCheckedItemsRef.current.filter((item) => !currentValue.includes(item.id)));
    } else {
      mergedCheckedItemsRef.current = uniqBy([...tempData, ...filteredCheckboxItems], 'id').filter(
        (item) => item.checked,
      );

      setRealCheckedItems(mergedCheckedItemsRef.current);
    }

    switch (type) {
      case '1':
        setCheckedPersonItemList(filteredCheckboxItems);
        setCheckedPersonIdList(filteredCheckboxItems.map((item) => item.id));

        break;
      case '2':
        setCheckedAssociationItemList(filteredCheckboxItems);
        setCheckedAssociationIdList(filteredCheckboxItems.map((item) => item.id));

        break;
      case '3':
        setCheckedPositionItemList(filteredCheckboxItems);
        setCheckedPositionIdList(filteredCheckboxItems.map((item) => item.id));

        break;
    }
  };

  /**
   * 移除选中 - 点击事件
   *
   * @param id
   * @param type
   */
  const onCheckedItemListDelete = (value: CheckboxItem) => {
    const { id, type, tab } = value;

    let filteredItemList, filteredIdList, filteredItemList2, filteredIdList2, filteredItemList3, filteredIdList3;

    mergedCheckedItemsRef.current = mergedCheckedItemsRef.current.filter((item) => item.id !== id);

    setRealCheckedItems(mergedCheckedItemsRef.current);

    switch (tab) {
      case '1':
        filteredItemList = checkedPersonItemList.filter((item) => item.id !== id);
        filteredIdList = checkedPersonIdList.filter((item) => item !== id);

        setCheckedPersonItemList(filteredItemList);
        setCheckedPersonIdList(filteredIdList);

        // filteredItemList2 = checkedAssociationItemList.filter((item) => item.id !== id && tab === '2');
        filteredItemList2 = checkedAssociationItemList.filter((item) => item.id !== id);
        filteredIdList2 = filteredItemList2.map((item) => item.id);

        setCheckedAssociationItemList(filteredItemList2);
        setCheckedAssociationIdList(filteredIdList2);

        filteredItemList3 = checkedPositionItemList.filter((item) => item.id !== id);
        filteredIdList3 = filteredItemList3.map((item) => item.id);

        setCheckedPositionItemList(filteredItemList3);
        setCheckedPositionIdList(filteredIdList3);

        break;
      case '2':
        filteredItemList = checkedAssociationItemList.filter((item) => item.id !== id);
        filteredIdList = checkedAssociationIdList.filter((item) => item !== id);

        setCheckedAssociationItemList(filteredItemList);
        setCheckedAssociationIdList(filteredIdList);

        filteredItemList2 = checkedPersonItemList.filter((item) => item.id !== id);
        filteredIdList2 = filteredItemList2.map((item) => item.id);

        setCheckedPersonItemList(filteredItemList2);
        setCheckedPersonIdList(filteredIdList2);

        break;
      case '3':
        filteredItemList = checkedPositionItemList.filter((item) => item.id !== id);
        filteredIdList = checkedPositionIdList.filter((item) => item !== id);

        setCheckedPositionItemList(filteredItemList);
        setCheckedPositionIdList(filteredIdList);

        filteredItemList2 = checkedPersonItemList.filter((item) => item.id !== id);
        filteredIdList2 = filteredItemList2.map((item) => item.id);

        setCheckedPersonItemList(filteredItemList2);
        setCheckedPersonIdList(filteredIdList2);

        break;
    }
  };

  /**
   * 下一级
   *
   * @param value
   */
  const nextClickHandler = async (value: CheckboxItem) => {
    let tempDataList, response;

    setLoading(true);

    switch (value.type) {
      case '1':
        setCheckedPersonItemList(realCheckedItems.filter((item) => item.type === '1'));
        setCheckedPersonIdList(realCheckedItems.filter((item) => item.type === '1').map((v) => v.id));

        break;
      case '2':
        isNextLevelRef.current = true;

        response = await getPersonListByEntId({ pageIndex: 1, pageSize: 10, entId: value.id });

        tempDataList = (response?.list as PersonDataVO[]).map((item, index) => {
          return {
            uniquedKey: new Date().getTime() + index + '2',
            name: item.name,
            id: item.personId,
            phone: item.phone,
            avatar: item.icon,
            count: 1,
            type: '1',
            tab: '2',
          };
        });

        setAssociationDataList(tempDataList);

        setSelectedEnterprisePersonTotal(response.total);
        setSelectedLevelItem(value);

        setCheckedAssociationItemList(
          realCheckedItems.filter((item) => item.type === '1').map((v) => ({ ...v, tab: '2' })),
        );
        setCheckedAssociationIdList(realCheckedItems.filter((item) => item.type === '1').map((v) => v.id));

        break;
      case '3':
        isNextLevelRef.current = true;
        response = await getPersonListByEntId({ pageIndex: 1, pageSize: 10, positionLabelCode: value.id });

        tempDataList = (response?.list as PersonDataVO[]).map((item, index) => {
          return {
            uniquedKey: new Date().getTime() + index + '2',
            name: item.name,
            id: item.personId,
            phone: item.phone,
            avatar: item.icon,
            count: 1,
            type: '1',
            tab: '2',
          };
        });

        setPositionDataList(tempDataList);

        setSelectedPositionPersonTotal(response.total);
        setSelectedLevelItem(value);

        setCheckedPositionItemList(
          realCheckedItems.filter((item) => item.type === '1').map((v) => ({ ...v, tab: '3' })),
        );
        setCheckedPositionIdList(realCheckedItems.filter((item) => item.type === '1').map((v) => v.id));

        break;
    }

    setLoading(false);
  };

  /**
   * 上一级
   */
  const previousClickHandler = async (value: CheckboxItem) => {
    let tempDataList, response;

    setLoading(true);
    isNextLevelRef.current = false;

    setSelectedEnterprisePersonTotal(0);
    setSelectedPositionPersonTotal(0);

    enterprisePageIndexRef.current = 1;
    positionPageIndexRef.current = 1;

    switch (value.type) {
      case '2':
        response = await getAssociationTreeData({ type: 1, count: true, entId: value.id ?? undefined });

        tempDataList = (response?.list as AssociationTreeDataVO[]).map((item, index) => {
          return {
            uniquedKey: new Date().getTime() + index + '2',
            name: item.name,
            id: item.entId,
            avatar: item.icon,
            count: +item.count,
            type: '2',
            tab: '2',
          };
        });

        setAssociationDataList(tempDataList);

        setCheckedAssociationItemList(realCheckedItems.filter((item) => item.tab === '2' && item.type === '2'));
        setCheckedAssociationIdList(
          realCheckedItems.filter((item) => item.tab === '2' && item.type === '2').map((v) => v.id),
        );

        break;
      case '3':
        response = await getPositionListByEntId({ entId });

        tempDataList = (response?.list as PositionDataVO[]).map((item, index) => {
          return {
            uniquedKey: new Date().getTime() + index + '3',
            name: item.name,
            id: item.code,
            count: item.personNum,
            type: '3',
            tab: '3',
          };
        });

        setPositionDataList(tempDataList);

        setCheckedPositionItemList(realCheckedItems.filter((item) => item.tab === '3' && item.type === '3'));
        setCheckedPositionIdList(
          realCheckedItems.filter((item) => item.tab === '3' && item.type === '3').map((v) => v.id),
        );

        break;
    }

    setLoading(false);
  };

  /**
   * 加载更多
   */
  const loadMoreData = () => {
    if (loading) {
      return;
    }

    ++pageIndexRef.current;

    if (pageIndexRef.current > Math.ceil(total / 10)) {
      return;
    }

    getPersonListByEntId({ pageIndex: pageIndexRef.current, pageSize: 10 }).then((res) => {
      const tempDataList = (res?.list as PersonDataVO[]).map((item, index) => {
        return {
          uniquedKey: new Date().getTime() + index + '1',
          name: item.name,
          id: item.personId,
          phone: item.phone,
          avatar: item.icon,
          count: 1,
          type: '1',
          tab: '1',
        };
      });

      setPersonDataList([...personDataList, ...tempDataList]);
    });
  };

  const loadEnterprisePersonList = () => {
    if (isNextLevelRef.current) {
      if (loading) {
        return;
      }

      ++enterprisePageIndexRef.current;

      if (enterprisePageIndexRef.current > Math.ceil(selectedEnterprisePersonTotal / 10)) {
        return;
      }

      getPersonListByEntId({
        pageIndex: enterprisePageIndexRef.current,
        pageSize: 10,
        entId: selectedLevelItem?.id,
      }).then((res) => {
        const tempDataList = (res?.list as PersonDataVO[]).map((item, index) => {
          return {
            uniquedKey: new Date().getTime() + index + '2',
            name: item.name,
            id: item.personId,
            phone: item.phone,
            avatar: item.icon,
            count: 1,
            type: '1',
            tab: '2',
          };
        });

        setAssociationDataList([...associationDataList, ...tempDataList]);
      });
    }
  };

  const loadPositionPersonList = () => {
    if (isNextLevelRef.current) {
      if (loading) {
        return;
      }

      ++positionPageIndexRef.current;

      if (positionPageIndexRef.current > Math.ceil(selectedPositionPersonTotal / 10)) {
        return;
      }

      getPersonListByEntId({
        pageIndex: positionPageIndexRef.current,
        pageSize: 10,
        positionName: selectedLevelItem?.name,
      }).then((res) => {
        const tempDataList = (res?.list as PersonDataVO[]).map((item, index) => {
          return {
            uniquedKey: new Date().getTime() + index + '2',
            name: item.name,
            id: item.personId,
            phone: item.phone,
            avatar: item.icon,
            count: 1,
            type: '1',
            tab: '2',
          };
        });

        setPositionDataList([...positionDataList, ...tempDataList]);
      });
    }
  };

  return (
    <>
      <YmDialog {...mergeModlaProps}>
        <div className={Ostyle.ym_register_person_modal} style={{ width: choiceBtn === 'checkbox' ? 668 : 320 }}>
          <div className={Ostyle.ym_register_person_modal_left}>
            <p className={Ostyle.ym_register_person_modal_left_flag}>选择</p>
            <div className={Ostyle.ym_register_person_modal_left_search}>
              <Input.Search placeholder="请输入姓名、手机号" onSearch={onSearch} allowClear={true} />
            </div>
            <div className={Ostyle.ym_register_person_modal_left_tabs}>
              <YmTabs
                activeKey={tabActiveKey}
                items={choiceTabItems}
                onChange={handleChoiceTabChange}
                noneedTabPane={true}
                tabBarStyle={{ fontSize: '14px' }}
                tabBarGutter={24}
                tabBarListStyle={{ justifyContent: 'flex-start' }}
              />
            </div>
            <div className={Ostyle.ym_register_person_modal_left_content}>
              <div
                className={classNames(Ostyle.content_section, {
                  [Ostyle.active]: tabActiveKey === '1',
                })}
              >
                <CheckboxList
                  tab="1"
                  loadMoreData={loadMoreData}
                  loading={loading}
                  mergedData={tempMergedDataList}
                  dataSource={personDataList}
                  total={total}
                  value={checkedPersonIdList}
                  onCheckboxItemChange={(checkedIds, checkedItems, currentValue, isChecked) =>
                    onCheckboxItemChange(checkedIds, checkedItems, currentValue, isChecked, '1')
                  }
                  onAllCheck={(checkedIds, checkedItems, currentValue, isChecked) =>
                    onAllCheckboxItemChange(checkedIds, checkedItems, currentValue, isChecked, '1')
                  }
                />
              </div>
              <div
                className={classNames(Ostyle.content_section, {
                  [Ostyle.active]: tabActiveKey === '2',
                })}
              >
                <CheckboxList
                  tab="2"
                  loading={loading || isLoading}
                  mergedData={tempMergedDataList}
                  dataSource={associationDataList}
                  loadMoreData={loadEnterprisePersonList}
                  total={selectedEnterprisePersonTotal}
                  defaultCrumbList={crumbList}
                  value={checkedAssociationIdList}
                  onCheckboxItemChange={(checkedIds, checkedItems, currentValue, isChecked) =>
                    onCheckboxItemChange(checkedIds, checkedItems, currentValue, isChecked, '2')
                  }
                  onAllCheck={(checkedIds, checkedItems, currentValue, isChecked) =>
                    onAllCheckboxItemChange(checkedIds, checkedItems, currentValue, isChecked, '2')
                  }
                  onNextClick={nextClickHandler}
                  onPreviousClick={previousClickHandler}
                />
              </div>

              <div
                className={classNames(Ostyle.content_section, {
                  [Ostyle.active]: tabActiveKey === '3',
                })}
              >
                <CheckboxList
                  tab="3"
                  loading={loading || isLoading}
                  mergedData={tempMergedDataList}
                  dataSource={positionDataList}
                  loadMoreData={loadPositionPersonList}
                  total={selectedPositionPersonTotal}
                  defaultCrumbList={crumbList}
                  value={checkedPositionIdList}
                  onCheckboxItemChange={(checkedIds, checkedItems, currentValue, isChecked) =>
                    onCheckboxItemChange(checkedIds, checkedItems, currentValue, isChecked, '3')
                  }
                  onAllCheck={(checkedIds, checkedItems, currentValue, isChecked) =>
                    onAllCheckboxItemChange(checkedIds, checkedItems, currentValue, isChecked, '3')
                  }
                  onNextClick={nextClickHandler}
                  onPreviousClick={previousClickHandler}
                />
              </div>
            </div>
          </div>

          <div className={Ostyle.ym_register_person_modal_center}>
            <DoubleRightOutlined className={Ostyle.ym_register_person_modal_center_arrow} />
          </div>

          <div className={Ostyle.ym_register_person_modal_right}>
            <p className={Ostyle.ym_register_person_modal_right_flag}>已选</p>
            <div className={Ostyle.ym_register_person_modal_right_selected}>
              <SelectedItemList dataSource={realCheckedItems} onDelete={onCheckedItemListDelete} />
            </div>
          </div>
        </div>
      </YmDialog>
    </>
  );
});

export default YmRegisterPersonModal;
